﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Smart.Common.Entities;
using Smart.Common.Notifications;

namespace Smart.Common.UserControls
{
	public partial class SendEmail : UserControl
	{
		public IEntityList<NotificationTemplate> Templates { get; set; }

		protected virtual string GetAccountsEmails(SPWeb web, INotificationScope notification)
		{
			var accounts =
				peSendTo.CommaSeparatedAccounts.IsNullOrEmpty()
					? string.Empty
					: peSendTo.CommaSeparatedAccounts;

			return
				accounts
					.SplitByCommaOrSemicolon()
					.Select(login => SPPrincipalExts.RemoveClaimsPrefix(login))
					.Select(account => notification.GetEmails(account))
					.CastToString(";");
		}

		protected virtual void Page_Load(object sender, EventArgs e)
		{
			if (IsPostBack)
				return;

			LoadTemplates();

			ddlTemplates.DataSource = Templates.OrderBy(t => t.Title);
			ddlTemplates.DataBind();

			ddlTemplates.SelectedValue = "-1";
		}

		protected virtual void LoadTemplates()
		{
			if (Templates != null)
				return;

			using (var scope = SPServices.Notifications)
			{
				Templates = scope.Templates.All;

				Templates.Add(new NotificationTemplate { ID = -1, Body = string.Empty, Title = string.Empty, Subject = string.Empty });
			}
		}

		protected virtual void TemplatesSelectedIndexChanged(object sender, EventArgs e)
		{
			LoadTemplates();

			var id = ddlTemplates.SelectedValue.SToInt(0);

			if (id <= 0) return;

			var currentTemplate = Templates.FindById(id);

			if (currentTemplate == null) return;

			tbBody.Text = currentTemplate.Body;
			tbSubject.Text = currentTemplate.Subject;
		}

		protected virtual void OnSendButtonClick(object sender, EventArgs e)
		{
			cvSending.Validate();

			if (!cvSending.IsValid) return;

			bool queued;

			using (var scope = SPServices.Notifications)
			{
				queued = scope.QueueItem(tbSubject.Text, tbBody.Text, tbSendToAdd.Text + ";" + GetAccountsEmails(scope.Web, scope), dtSendAt.IsDateEmpty ? DateTime.Now : dtSendAt.SelectedDate);
			}

			if (!queued)
			{
				divMessage.InnerText = "SendEmailError".Localized();
			}
			else
			{
				RedirectToSource();
			}
		}

		protected virtual void ServerValidateSend(object source, ServerValidateEventArgs args)
		{
			if (peSendTo.ResolvedEntities.Count != 0 || !tbSendToAdd.Text.IsNullOrEmpty())
			{
				args.IsValid = true;
				return;
			}

			using (var scope = SPServices.Notifications)
			{
				if (!scope.ValidateEmails(tbSendToAdd.Text).IsNullOrEmpty()) return;

				args.IsValid = false;
			}
		}

		protected virtual void OnCancelButtonClick(object sender, EventArgs e)
		{
			RedirectToSource();
		}

		[Localizable(false)]
		protected virtual void RedirectToSource()
		{
			Response.Redirect(Request["Source"] ?? "~/_layouts/settings.aspx");
		}
	}
}
